<template>
  <div>
    <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>

   <!-- 背景卡片 -->
  <el-card class="box-card">
    <el-row>
      <el-col>
        <el-button type="primary">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 渲染数据表格 -->
    <el-table
      :data="roleList"
      border
      stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 添加边框线，如果索引为0，在加一个上边框 -->
          <!-- 一共三级权限，通过三个for遍历出来 -->
          <!-- 一级权限 -->
          <el-row :class="['el-bottom','vcenter', index1 === 0 ? 'el-top' : '']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
             <el-col :span="5" >
               <el-tag closable @close='removeRightById(scope.row, item1.id)'>{{item1.authName}}</el-tag>
               <!-- 箭头图标 -->
               <i class="el-icon-caret-right"></i>
             </el-col>
             <!-- 二级权限 v-for从一级权限item中的children获取-->
             <el-col :span="19">
               <el-row :class="['vcenter',index2 === 0 ? '' : 'el-top']" v-for="(item2,index2) in item1.children" :key="item2.id">
                 <el-col :span="6">
                   <el-tag type="success" closable @close='removeRightById(scope.row, item2.id)'>{{item2.authName}}</el-tag>
                   <!-- 箭头图标 -->
                  <i class="el-icon-caret-right"></i>
                 </el-col>
                 <!-- 三级权限 -->
                 <el-col :span="13" >
                   <el-tag closable @close='removeRightById(scope.row, item3.id)' type="warning" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                 </el-col>
               </el-row>
             </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- type="index" 添加索引，默认从1开始++ -->
      <el-table-column type="index"></el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名称">
      </el-table-column>
      <el-table-column
        prop="roleDesc"
        label="角色描述">
      </el-table-column>
      <el-table-column
        label="操作"
        width="300px">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="openRightDialogVisible(scope.row)">分配权限</el-button>
        </template>

      </el-table-column>
    </el-table>
  </el-card>

  <!-- 分配权限的dialog对话框 -->
    <el-dialog
    title="分配权限"
    :visible.sync="setRightDialogVisible"
    width="40%"
    @close="setRightDialogClosed">
    <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
    :default-checked-keys="defKeys" ref="treeRef"></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="updateRights">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 树形控件默认选中的节点
      defKeys: [],
      roleId: ''
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.roleList = res.data
      // console.log(res.data)
    },
    // 监听权限移除，tag标签删除的事件
    async removeRightById(role, rigthId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // console.log(confirmResult)
        if (confirmResult === 'confirm') {
          // 发送请求
          const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rigthId}`)
          if (res.meta.status !== 200) return this.$message.err('删除权限失败！')
          // 如果删除成功，将返回的值res.data直接给role，res.data是删除后返回的新的权限集合，让其直接渲染页面，不需要调用getRolesList
          role.children = res.data
        }
    },
    // 监听分配用户对话框的显示与隐藏，并获取用户权限列表
    async openRightDialogVisible(role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.err('获取用户权限数据失败！')
      this.rightsList = res.data

      this.getLeafKeys(role, this.defKeys)
      console.log(this.defKeys)

      // 拿到当前操作的ID保存起来，用于修改更新用户的权限
      this.roleId = role.id
      this.setRightDialogVisible = true
    },
    // 利用递归的形式，遍历出三级节点，并赋值给defKeys，让树状控件默认勾选已有权限
    getLeafKeys(node, arr) {
      if (!node.children) {
        // 如果不包含children，说明就是三级节点，就把id给arr保存起来
        return arr.push(node.id)
      }
      node.children.forEach(item => {
       this.getLeafKeys(item, arr)
      })
    },
    // 分配权限的对话框每次关闭后，清空defkeys数组
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 根据用户勾选的权限，来更新修改用的的权限
    async updateRights() {
      // getHalfCheckedKeys,返回目前半选中的节点的key所组成的数组
      // getCheckedKeys,返回目前被选中的节点的key所组成的数组
      // 将这两个返回值拼接成一个新数组，在转成字符串，作为请求参数传递
      const keys = [
      ...this.$refs.treeRef.getCheckedKeys(),
      ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keyStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keyStr })
      if (res.meta.status !== 200) return this.$message.err('修改用户权限失败！')

      this.$message.success('修改用户权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.el-top{
  border-top: 1px solid #eee;
}
.el-bottom{
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
